import React, { useState, useCallback, useMemo } from 'react'
import { Image, Text, View } from '@tarojs/components'
import SurveyHeader from '@COMPONENTS/Survey/SurveyHeader'
import styles from '@COMPONENTS/Survey/SurveySubChoice.module.scss'
import Images from '@ASSET/Images'

const getSubData = choices => {
  const len = choices.length
  const res = {}
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < len; i++) {
    const { SubChoices, Label: mainLabel } = choices[i]
    const subLen = Array.isArray(SubChoices) ? SubChoices.length : 0
    const subRes = []
    if (subLen > 0) {
      SubChoices.forEach(item => {
        const { Label } = item
        subRes.push(Label)
      })
    }
    res[mainLabel] = subRes
  }
  return res
}
const TYPE_KEY = {
  SingleSubChoice: {
    selectKey: 'AnswerChoice',
    dataKey: 'Choices',
  },
  MultipleSubChoice: {
    selectKey: 'AnswerChoices',
    dataKey: 'Choices',
  },
}

const SurveySubChoice = ({
  data, language, onChange, disabled, questionType, ordinal, required, isShowTopLine, submitted, isSingle
}) => {
  const { Level, QuestionText, QuestionStyle, Choices } = data
  const [openLabel, setOpenLabel] = useState(undefined)

  const subData = useMemo(() => getSubData(Choices), [Choices])
  const key = TYPE_KEY[QuestionStyle]
  const { selectKey, dataKey } = key || {}
  const selectData = data[selectKey]
  const choices = data[dataKey]
  const onChangeItem = useCallback(item => {
    if (isSingle) {
      const newSelectData = selectData === item.Label ? '' : item.Label
      onChange?.({ ...data, [selectKey]: newSelectData })
    } else {
      const index = selectData.indexOf(item.Label)
      if (index > -1) {
        selectData.splice(index, 1)
      } else {
        selectData.push(item.Label)
      }
      const newItem = { ...data, [selectKey]: selectData }
      onChange?.(newItem)
    }
  }, [data, isSingle, onChange, selectData, selectKey])

  const onPressItem = useCallback((item, subChoices) => {
    if (disabled) return
    if (Array.isArray(subChoices) && subChoices.length > 0) {
      setOpenLabel(openLabel === item.Label ? undefined : item.Label)
      return
    }
    openLabel && !item.SubChoice && setOpenLabel(undefined)
    onChangeItem?.(item)
  }, [disabled, onChangeItem, openLabel])

  if (!key) return null
  return (
    <View>
      <SurveyHeader
        level={Level}
        questionType={questionType}
        label={QuestionText?.[language]}
        ordinal={ordinal}
        required={required}
        isShowTopLine={isShowTopLine}
      />
      <View className={styles.container}>
        {choices.map(item => (
          <ChoiceItem
            key={item.Label}
            data={item}
            disabled={disabled}
            selectData={selectData}
            mainData={subData}
            language={language}
            onPressItem={onPressItem}
            openLabel={openLabel}
            submitted={submitted}
            isSingle={isSingle}
          />
        ))}
      </View>
    </View>
  )
}

const getSrc = (isSelect, hasSubChoices, SubChoice, isMainSelect, showSubChoices) => {
  if (!hasSubChoices) {
    return isSelect
      ? Images.survey.icon_survey_select
      : Images.survey[`icon_survey_${SubChoice ? 'sub_' : ''}normal`]
  }
  const status = showSubChoices ? 'open' : 'close'
  const select = isMainSelect ? 'select' : 'unselect'
  return Images.survey[`icon_${status}_${select}`]
}

const ChoiceItem = ({
  data, selectData, mainData, disabled, onPressItem, language, openLabel, submitted, isSingle,
}) => {
  const { Text: text, Label, SubChoices, SubChoice } = data || {}
  const isSelect = isSingle ? selectData === Label : selectData?.includes(Label)
  const isMainSelect = mainData?.[Label].find(item => (isSingle ? selectData === item : selectData.includes(item)))
  const hasSubChoices = Array.isArray(SubChoices) && SubChoices.length > 0
  const showSubChoices = (hasSubChoices && openLabel === Label) && !submitted
  const showSelectLine = isSelect || isMainSelect
  const extraText = SubChoices?.filter(item => (isSingle ? item.Label === selectData : selectData.includes(item.Label)))
    .map(item => item.Text?.[language])
    .join('/') || ''
  const src = showSelectLine && submitted
    ? Images.survey.icon_survey_select
    : getSrc(isSelect, hasSubChoices, SubChoice, isMainSelect, showSubChoices)

  return (
    <>
      <View
        className={styles.item}
        disabled={disabled}
        onClick={() => onPressItem(data, SubChoices)}
        key={Label}
      >
        {showSelectLine && <View className={styles.lineBg} />}
        <Text className={`${styles.label} ${disabled ? styles.labelDisabled : ''} ${showSelectLine ? styles.labelSelect : ''}`}>
          {`${Label}. `}
        </Text>
        <Text
          className={`${styles.label} ${disabled ? styles.labelDisabled : ''} ${showSelectLine ? styles.labelSelect : ''}`}
          style={{ flex: 1 }}
        >
          {text?.[language]}
          {!!extraText && <Text className={styles.extraText}>{`(${extraText})`}</Text>}
        </Text>
        {(!disabled || showSelectLine) && (
          <View className={styles.selectIconView}>
            <Image src={src} className={styles.icon} />
          </View>
        )}
      </View>
      {
        showSubChoices && (
          <View className={styles.subContainer}>
            {
              SubChoices.map(item => (
                <ChoiceItem
                  key={item.Label}
                  data={item}
                  disabled={disabled}
                  selectData={selectData}
                  language={language}
                  onPressItem={onPressItem}
                  openLabel={openLabel}
                />
              ))
            }
          </View>
        )
      }
    </>
  )
}

export default SurveySubChoice
